package com.example.payment.repository;

import com.example.payment.entity.PaymentOrder;
import com.example.payment.enums.PaymentStatus;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Repository
public interface PaymentOrderRepository extends JpaRepository<PaymentOrder, Long> {
    
    Optional<PaymentOrder> findByOrderNo(String orderNo);
    
    Optional<PaymentOrder> findByBusinessOrderNo(String businessOrderNo);
    
    List<PaymentOrder> findByUserId(Long userId);
    
    List<PaymentOrder> findByUserIdAndStatus(Long userId, PaymentStatus status);
    
    List<PaymentOrder> findByStatus(PaymentStatus status);
    
    @Query("SELECT p FROM PaymentOrder p WHERE p.status = :status AND p.expiredAt < :now")
    List<PaymentOrder> findExpiredOrders(@Param("status") PaymentStatus status, @Param("now") LocalDateTime now);
    
    @Query("SELECT p FROM PaymentOrder p WHERE p.userId = :userId AND p.businessType = :businessType")
    List<PaymentOrder> findByUserIdAndBusinessType(@Param("userId") Long userId, @Param("businessType") String businessType);
    
    @Query("SELECT COUNT(p) FROM PaymentOrder p WHERE p.userId = :userId AND p.status = :status AND p.createdAt >= :startTime")
    long countByUserIdAndStatusAndTimeRange(@Param("userId") Long userId, 
                                          @Param("status") PaymentStatus status, 
                                          @Param("startTime") LocalDateTime startTime);
} 